package com.ciwong.epaper.modules.evaluate.ui;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.common.guidedialog.CountDownDialog;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.epaper.util.RepeatKeyUtil;
import com.ciwong.epaper.modules.evaluate.bean.Sentence;
import com.ciwong.epaper.modules.evaluate.bean.SentenceAnswerBean;
import com.ciwong.epaper.modules.evaluate.bean.SentencesDetail;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.modules.evaluate.util.ScoreTipsDialog;
import com.ciwong.epaper.modules.evaluate.util.SentenceResultScoreController;
import com.ciwong.epaper.modules.evaluate.util.SpeechUtils;
import com.ciwong.epaper.modules.me.bean.RequirementContent;
import com.ciwong.epaper.modules.me.bean.WorkContents;
import com.ciwong.epaper.modules.me.ui.JsonParserUtil;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.util.ALiYunManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.ScoreUtils;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.widget.NewLoginDialog;
import com.ciwong.epaper.widget.PlayStateDubView;
import com.ciwong.epaper.widget.PlayStateView;
import com.ciwong.epaper.widget.evaluate.SentenceSpeechView;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.audio.play.OnPlayListener;
import com.ciwong.libs.oralevaluate.bean.EvaluateResult;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.BuyServiceDialog;
import com.ciwong.mobilelib.widget.CWDialog;
import com.google.gson.reflect.TypeToken;
import com.unisound.edu.oraleval.sdk.sep15.IOralEvalSDK;
import com.unisound.edu.oraleval.sdk.sep15.SDKError;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 句子跟读 Created by lzr on 2017/4/7.
 */
public class SentenceRepeatActivity extends BaseActivity
        implements SpeechPlayController.SpeechPlayInterFace, SentenceResultScoreController.SentenceResultInterFace,
        CountDownDialog.CountInterFace, SentenceSpeechView.StressInterFace {

    protected DownLoadInfo mDownLoadInfo;

    protected Module mModule;

    protected RequirementContent requirementContent;

    protected int position;

    protected String intentWorkId = "0";

    // 有选题的情况
    protected String checkedResource;

    protected String mClassId;

    protected int mServiceId;

    protected int contentId;

    private long effectiveDate = -1;
    //需要重新评分的句子集合
    private List<Sentence> mScoreSentence = new ArrayList<>();

    private ScoreTipsDialog scoreTipsDialog;

    // ------------------
    // 播放状态动画控件
    protected PlayStateView stateView;

    // 播放全文
    protected TextView playAllView;

    protected ImageView startImg, iv_english_china;

    // 句子跟读显示句子的控件
    protected SentenceSpeechView speechView;

    // 记录句子
    protected ArrayList<SentencesDetail> sentencesDetails;

    // 语音播放的控制中心
    protected SpeechPlayController speechPlayController;

    protected RelativeLayout mRlCheckMode;

    protected ImageView mIvCheckMode;//

    protected TextView tv_mode;

    // 是否手动模式
    public boolean mIsUnAutoMode = false;

    //是否考试模式
    public boolean mIsKaoShiMode = false;
    //跟读模式 用于重读跳转
    public boolean mReadMode = false;

    // 进度条控件相关
    private TextView currText, countText;

    private ProgressBar progressBar;

    private TextView finishRecodeText; // 停止录音

    private View tipRec;

    // 头部控件
    protected View sumView;

    // 打分相关
    private RelativeLayout scoreRel;

    private TextView scoreText;

    private TextView scoreTextView;

    private TextView read_top_play_all;
    //记录是否重评完所有
    private int countIsScoreAll;
    //所有需要重评的句子数量
    private int allScoreCount;
    //以评分句子数量
    private int hasScoreCount;

    private ImageView scoreIma;

    // 学习记录相关
    private RelativeLayout studentRel;

    public static final int CODE_REQUEST_RECORD_AUDIO_PERMISSION = 8801;

    // 提交相关
    private RelativeLayout playRel;

    private TextView upWorkText;

    protected long startDate = System.currentTimeMillis();// (开始做作业时间)(毫秒

    Handler handler = new Handler();

    private long startTime;
    protected CountDownDialog countDownDialog;

    /**
     * 操作模式：逐句跟读、选段背诵、独立通读、单词跟读
     */
    protected int readMode;

    private long countTime = 0; // 跟读的总时间

    protected String titleText;

    // 是否允许播放
    private boolean isCanPlay;

    // 退出时候提示保存
    private boolean isBackSave = true;

    public static final int REQUEST_CODE_AN = 1000;

    private WorkContents mWorkContents;

    // 做题记录
    protected String mUuid = UUID.randomUUID().toString();

    private String mVerisonId;

    private String resourcePath;

    protected boolean isInSentenceAll = false;
    private TextView completion_text;
    private TextView see_work_score_text;
    private TextView smooth_text;
    private TextView accuracy_text;

    private EApplication application;

    /**
     * 默认服务包剩余使用时间
     */
    public boolean serviceExpired;
    /**
     * 评分系数
     */
    protected float mScoreCoefficient = 1;

    private boolean isRecording;

    private SentenceResultScoreController sentenceResultScoreController;

    private boolean isFinish;

    @Override
    protected void preCreate() {
        super.preCreate();
        Intent intent = getIntent();
        TAG = "retryscore2";

        if (intent != null) {
            try {
                readMode = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_TYPE,
                        SpeechPlayController.LISTENER_MODE_ZHUJU);
                mDownLoadInfo = (DownLoadInfo) intent.getSerializableExtra(
                        IntentFlag.INTENT_FLAG_DOWNLOAD_INFO);
                mModule = (Module) intent
                        .getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);

                requirementContent = (RequirementContent) intent
                        .getSerializableExtra(
                                IntentFlag.INTENT_FLAG_REQU_CONTENT);
                checkedResource = intent.getStringExtra(
                        IntentFlag.INTENT_FLAG_CHECKED_RESOURCE);
                position = intent.getIntExtra(IntentFlag.INTENT_FLAG_POSITION,
                        0);

                String workId = intent
                        .getStringExtra(IntentFlag.INTENT_FLAG_WORK_ID);
                mClassId = intent
                        .getStringExtra(IntentFlag.INTENT_FLAG_CLASS_ID);
                mServiceId = getIntent()
                        .getIntExtra(IntentFlag.INTENT_FLAG_SERVICE_ID, -1);
                contentId = getIntent()
                        .getIntExtra(IntentFlag.INTENT_FLAG_CONTENTID, 0);

                mWorkContents = (WorkContents) getIntent().getSerializableExtra(
                        IntentFlag.INTENT_FLAG_WORK_CONTENTS);

                effectiveDate = getIntent().getLongExtra(IntentFlag.INTENT_FLAG_WORK_EFFECTIV_TIME, -1);
                if (!TextUtils.isEmpty(workId)) {
                    intentWorkId = workId;
                }

                if (mDownLoadInfo
                        .getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_NEW) {
                    mVerisonId = mDownLoadInfo.getVersionId();
                    titleText = mDownLoadInfo.getResourceName();
                    resourcePath = ESystem.getPackagesJsonPathNew(
                            mDownLoadInfo.getBookId(),
                            mDownLoadInfo.getChapterId(),
                            mDownLoadInfo.getModuleId(),
                            mDownLoadInfo.getVersionId());

                } else {
                    resourcePath = ESystem.getPackagesJsonPath(mModule
                            .getResourceList().get(position).getResourceFile());
                    mVerisonId = mModule.getResourceList().get(position)
                            .getVersionId();
                    titleText = mModule.getResourceList().get(position)
                            .getResourceName();
                }
                //获取保存本地开始时间
                scoreTipsDialog = new ScoreTipsDialog(this);
                scoreTipsDialog.setCanceledOnTouchOutside(false);//点击屏幕 dialog不消失
                scoreTipsDialog.setCancelable(false);//点击屏幕或返回按钮 dialog不消失
                startTime = CWSys.getSharedLong(ListenSpeakUtil.getAnswerStartTimeKey(mDownLoadInfo, mModule, position, intentWorkId), 0);
                //本地没有则使用传过来的时间 并保存本地
                if (startTime == 0) {
                    if (null != mDownLoadInfo) {
                        startTime = mDownLoadInfo.getStartTime();
                        CWSys.setSharedLong(ListenSpeakUtil.getAnswerStartTimeKey(mDownLoadInfo, mModule, position, intentWorkId), startTime);
                    }
                }

            } catch (NullPointerException e) {
                e.getStackTrace();
            }

        }

    }

    @Override
    protected int setView() {
        return R.layout.sentence_repeat;
    }

    @Override
    protected void findViews() {
        speechView = findViewById(R.id.speechView);
        speechView.setStressInterFace(this);
        stateView = findViewById(R.id.play_state_iocn);
        startImg = findViewById(R.id.iv_stopOrplay);
        iv_english_china = findViewById(R.id.iv_english_china);
        startImg.setTag("play");
        playAllView = findViewById(R.id.paly_all);
        completion_text = findViewById(R.id.completion_text);
        see_work_score_text = findViewById(R.id.see_work_score_text);
        smooth_text = findViewById(R.id.smooth_text);
        accuracy_text = findViewById(R.id.accuracy_text);
        // 进度条相关
        currText = findViewById(R.id.btn_repeat_read_no);
        countText = findViewById(R.id.btn_repeat_read_count);
        progressBar = findViewById(R.id.progressBar);
        sumView = findViewById(R.id.top_view);
        sumView.setVisibility(View.GONE);
        // 打分相关
        scoreRel = findViewById(R.id.score_rel);
        scoreText = findViewById(R.id.score_text);
        scoreTextView = findViewById(R.id.score_fen);
        scoreIma = findViewById(R.id.score_fuhao);
        // 记录相关
        studentRel = findViewById(R.id.student_jilu);
        // 提交相关
        playRel = findViewById(R.id.play_rel);
        upWorkText = findViewById(R.id.up_work_but);

        // 录音相关
        finishRecodeText = findViewById(R.id.finsh_reco);
        tipRec = findViewById(R.id.show_reco_tip);

        mRlCheckMode = findViewById(R.id.rl_check_mode);
        mIvCheckMode = findViewById(R.id.iv_check_mode);

        back_record = findViewById(R.id.back_record);
        next_record = findViewById(R.id.next_record);
        img_micro_recording = findViewById(R.id.img_micro_recording);
        img_stop_recording = findViewById(R.id.img_stop_recording);
        play_iocn = findViewById(R.id.play_iocn);
        play_dubing_iocn = findViewById(R.id.play_dubing_iocn);
        read_top_play_all = findViewById(R.id.read_top_play_all);

        tv_mode = findViewById(R.id.tv_mode);
        tv_mode.setText("绘本模式");
        // 重读没有精读模式
        if (false) {
            mRlCheckMode.setVisibility(View.GONE);
        } else {
            mRlCheckMode.setVisibility(View.VISIBLE);
        }
    }

    protected TextView back_record, next_record;

    protected ImageView play_iocn, img_stop_recording, img_micro_recording;

    protected PlayStateDubView play_dubing_iocn;

    @Override
    protected void initEvent() {
        startImg.setOnClickListener(clickListener);
        playAllView.setOnClickListener(clickListener);
        iv_english_china.setOnClickListener(clickListener);
        upWorkText.setOnClickListener(clickListener);
        finishRecodeText.setOnClickListener(clickListener);
        mRlCheckMode.setOnClickListener(clickListener);
        back_record.setOnClickListener(clickListener);
        next_record.setOnClickListener(clickListener);
        read_top_play_all.setOnClickListener(clickListener);

        img_micro_recording.setOnClickListener(clickListener);
        img_stop_recording.setOnClickListener(clickListener);
        play_dubing_iocn.setOnClickListener(clickListener);
        play_iocn.setOnClickListener(clickListener);
        stateView.setClickListener(clickListener);
    }

    private ViewOnClickListener clickListener = new ViewOnClickListener(1000) {
        @Override
        public void avertRepeatOnClick(View v) {
            int id = v.getId();
            if (id == R.id.iv_stopOrplay) {
                if (v.getTag().equals("play")) {
                    // 播放
                    playImg();
                } else {
                    // 暂停播放
                    stopImg(true);
                }
            } else if (id == R.id.paly_all) {
                // 播放全文
                EpaperJumpManager.jumpToSentenceAll(R.string.go_back,
                        SentenceRepeatActivity.this, sentencesDetails, mModule,
                        position, mDownLoadInfo);
            } else if (id == R.id.read_top_play_all) {
                // 手动模式下播放全文
                EpaperJumpManager.jumpToSentenceAll(R.string.go_back,
                        SentenceRepeatActivity.this, sentencesDetails, mModule,
                        position, mDownLoadInfo);
            } else if (id == R.id.iv_english_china) {
                // 显示中文翻译
                speechView.setShowTranslateMole(!iv_english_china.isSelected(), speechPlayController.getCurrentListenAndRepeatIndex());
                iv_english_china.setSelected(!iv_english_china.isSelected());
            } else if (id == R.id.up_work_but) {
                submitWork();
            } else if (v.getId() == R.id.finsh_reco) {
                // 停止录音,提前完成录音
                speechPlayController.stopRecord();
            } else if (id == R.id.img_stop_recording) {
                // 完成、停止录音
                speechPlayController.stopRecord();
            } else if (id == R.id.rl_check_mode) {
                speechPlayController.setTempIndex(0);
                if (mIsUnAutoMode) {
                    cancelRecord();
                } else {
                    cancelRecord();
                    stopImg(true);
                }
                // 开启绘本模式
                showCheckModeDailog(mIvCheckMode.isSelected());
            } else if (id == R.id.play_iocn) {
                if (isRecording) {
                    return;
                }
                if (play_dubing_iocn != null && play_dubing_iocn.isPlay()) {
                    play_dubing_iocn.stopOnlyPlay();
                }
                // 播放题目
                startUnAutoPlay();
            } else if (id == R.id.img_micro_recording) {
                // 录音
                speechPlayController.setIsPause(false);
                if (!mIsUnAutoMode) {
                    return;
                }
                cancelRecord();
                if (AudioPlayer.getInstance().isPlaying()) {
                    AudioPlayer.getInstance().stop();
                }
                speechPlayController.startRecordHint(
                        speechPlayController.getCurrentListenAndRepeatIndex());
                setRecordStatus();
            } else if (id == R.id.back_record) {
                // 上一个
                if (isRecording) {
                    return;
                }
                if (speechPlayController.getCurrentListenAndRepeatIndex() > 0) {
                    speechView.previousCount(speechPlayController.getCurrentListenAndRepeatIndex());
                }
                stopImg(true);
                speechView.playUnAto(false);
                if (speechPlayController.getCurrentListenAndRepeatIndex() <= 0) {
                    ToastUtil.INSTANCE.toastInCenter(
                            SentenceRepeatActivity.this, "已经是第一个了");
                    return;
                }
                cancelRecord();
                if (AudioPlayer.getInstance().isPlaying()) {
                    AudioPlayer.getInstance().stop();
                }
                setRecordStatus();
                speechPlayController.setCurrentListenAndRepeatIndex(
                        speechPlayController.getCurrentListenAndRepeatIndex()
                                - 1);
                speechView.toTop();
                nextPlay(speechPlayController.getCurrentListenAndRepeatIndex(),
                        speechPlayController.getSentences().size(), true);
            } else if (id == R.id.next_record) {
                // 下一个
                if (isRecording) {
                    return;
                }
                if (speechPlayController
                        .getCurrentListenAndRepeatIndex() >= sentencesDetails
                        .size()) {
                    return;
                }
                stopRecord();
                if (AudioPlayer.getInstance().isPlaying()) {
                    AudioPlayer.getInstance().stop();
                }
                setRecordStatus();
                lastRecord(
                        speechPlayController.getCurrentListenAndRepeatIndex(),
                        speechPlayController.getSentences().size());
                speechPlayController.setCurrentListenAndRepeatIndex(
                        speechPlayController.getCurrentListenAndRepeatIndex()
                                + 1);
                speechView.toTop();
                nextPlay(speechPlayController.getCurrentListenAndRepeatIndex(),
                        speechPlayController.getSentences().size(), false);
                //点击下一个自动播放音频
                if (speechPlayController.getCurrentListenAndRepeatIndex() >= speechPlayController.getSentenceAnswers().size()
                        && speechPlayController.getCurrentListenAndRepeatIndex() <= speechPlayController.getSentences().size() - 1) {
                    speechPlayController.setIsPause(false);
                    speechPlayController.play();
                }
            } else if (id == R.id.play_dubing_iocn) {
                if (isRecording) {
                    return;
                }
                // 播放录音
                playRecordWord();
            }
        }
    };

    @Override
    public void showResult(EvaluateResult er, Sentence sentence, boolean isFill) {
        speechView.showResult(er, sentence, isFill, serviceExpired);
    }

    private void submitWork() {
        // 提交作业
        if (EConstants.IS_YOUKE) {
            EConstants.SENTENCE_IS_YOUKE_LOGIN = true;
            NewLoginDialog newLoginDialog = new NewLoginDialog(
                    SentenceRepeatActivity.this);
            newLoginDialog.showLoginDialog();

        } else {
            if (!NetworkUtils.isOnline()) {
                Toast toast = Toast.makeText(SentenceRepeatActivity.this,
                        "网络不可用,请连接网络后重试!", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                toast.show();
                return;
            }
            //需要重新评分的答案集合
            if (null != mScoreSentence) {
                //清除list避免重复提交叠加
                mScoreSentence.clear();
            }
            for (int i = 0; i < speechPlayController.getSentenceAnswers().size(); i++) {
                if (speechPlayController.getSentenceAnswers().get(i).getSentence().getScore() == -1) {
                    mScoreSentence.add(speechPlayController.getSentenceAnswers().get(i).getSentence());
                }
            }
            if (mScoreSentence.size() > 0) {
                allScoreCount = mScoreSentence.size();
                hasScoreCount = 0;
                countIsScoreAll = 0;
                showTips();
               /* for (int i = 0; i < scoreAnswer.size(); i++) {
                    if (i == scoreAnswer.size() - 1) {
                        scoreReTry(true, scoreAnswer.get(i).getSentence());
                    } else {
                        scoreReTry(false, scoreAnswer.get(i).getSentence());
                    }
                }*/
                scoreReTryCommit();

            } else {
                // 提交之前改变状态并且保持在本地
                onSaveState(SentenceResultActivity.SENTENCE_STATE_DEF);

                onSaveSentenceRecord(speechPlayController.getSentenceAnswers());

                EpaperJumpManager.jumpToSentenceResult(R.string.go_back,
                        SentenceRepeatActivity.this, intentWorkId, mDownLoadInfo,
                        mModule, requirementContent, position, readMode, mServiceId,
                        mClassId, contentId,
                        speechPlayController.getSentenceAnswers(),
                        SentenceResultActivity.SENTENCE_STATE_DEF, mWorkContents, effectiveDate);

                finish();
            }
        }
    }

    @Override
    protected void init() {
        String uuidkey = RepeatKeyUtil.getUuidSaveKey(mDownLoadInfo, mModule,
                position, intentWorkId, readMode);
        application = (EApplication) getApplication();
        if (application != null) {
            //学习中心
            serviceExpired = application.isServiceExpired();
        }
        if (!serviceExpired) {
            if (mWorkContents != null && mWorkContents.getIsFree() == 1) {
                serviceExpired = true;
            }
        }
        final String saveUUid = CWSys.getSharedString(uuidkey, null);
        if (null != saveUUid) {
            startDate = CWSys.getSharedLong(getStartTime(),
                    System.currentTimeMillis());
            mUuid = saveUUid;
            countTime = (int) (System.currentTimeMillis() - startDate);
            long oldCountTime = CWSys.getSharedLong(getSaveTime(), 0);
            if (countTime < oldCountTime || countTime < 0) {
                countTime = oldCountTime;
            }
        } else {
            CWSys.setSharedString(uuidkey, mUuid);
            CWSys.setSharedLong(getStartTime(), startDate);
        }

        // 设置评分系数
        ScoreUtils.setSocreCoefficient();
        setTitleText(titleText);
        setGoBackListener(new GoBackListener() {
            @Override
            public void goBack() {
                showDialog();
            }
        });
        String text = "查看分数";
        SpannableString spannableString = new SpannableString(text);
        spannableString.setSpan(new UnderlineSpan(), 0, text.length(), 0);
        see_work_score_text.setText(spannableString);
        see_work_score_text.setOnClickListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                setBuyServiceDialog();
            }
        });

    }

    private BuyServiceDialog buyServiceDialog;

    public void setBuyServiceDialog() {
        if (buyServiceDialog == null) {
            buyServiceDialog = new BuyServiceDialog(SentenceRepeatActivity.this);
            buyServiceDialog.setMenuOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    //购买服务包
                    MeJumpManager.jumpBuyService(SentenceRepeatActivity.this, R.string.go_back, mServiceId, -1, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY, "");
                    buyServiceDialog.dismiss();
                }
            });
            buyServiceDialog.setClosOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    buyServiceDialog.dismiss();
                }
            });
        }
        buyServiceDialog.show();
    }

    /**
     * 获取作业开始时间key
     *
     * @return
     */
    protected String getStartTime() {
        String key = ESystem.getSaveRecordKeywithMode(mDownLoadInfo, mModule,
                position, intentWorkId,
                SerializableManager.SerializeKey.SHARE_KEY_DO_WORK_START_TIME,
                readMode);
        return key + "_" + getUserInfoBase().getUserId();
    }

    /**
     * 第一次的引导页以及倒计时
     */
    private void showHelp() {
        boolean isShowHelp = CWSys
                .getSharedBoolean(EConstants.SHARE_KEY_REPEAT_READ_HELP_TIP
                        + getUserInfoBase().getUserId(), true);
        if (isShowHelp) {
            final Dialog dialog = new Dialog(this, R.style.MyDialogStyle_Dim);
            dialog.setCancelable(false);
            dialog.setContentView(R.layout.dialog_repeat_read_tip);
            dialog.findViewById(R.id.tv_know)
                    .setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                            showCountDialog();
                        }
                    });
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog1) {
                    CWSys.setSharedBoolean(
                            EConstants.SHARE_KEY_REPEAT_READ_HELP_TIP
                                    + getUserInfoBase().getUserId(),
                            false);
                }
            });
            dialog.show();
        } else {
            showCountDialog();
        }
    }

    /**
     * 第一次显示完成录音给的提示
     */
    private void showFirstRec() {
        boolean isShowHelp = CWSys
                .getSharedBoolean(EConstants.SHARE_KEY_STOP_RECORD_TIP
                        + getUserInfoBase().getUserId(), true);
        if (isShowHelp) {
            if (tipRec != null) {
                tipRec.setVisibility(View.VISIBLE);
            }
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    tipRec.setVisibility(View.GONE);
                }
            }, 1500);
            CWSys.setSharedBoolean(EConstants.SHARE_KEY_STOP_RECORD_TIP
                    + getUserInfoBase().getUserId(), false);
        }
    }

    /**
     * 重新评分提示
     */
    public void showTips() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (scoreTipsDialog.isShowing()) {
                    scoreTipsDialog.setScoreCount(hasScoreCount, allScoreCount);
                } else {
                    if (null != scoreTipsDialog) {
                        scoreTipsDialog.show();
                        scoreTipsDialog.setScoreCount(hasScoreCount, allScoreCount);
                    }
                }
            }
        });

    }

    /**
     * 显示倒计时dialog
     */
    private void showCountDialog() {
        if (mIsUnAutoMode) {
            return;
        }
        countDownDialog = new CountDownDialog(this, this);
        countDownDialog.setCancelable(false);
        countDownDialog.show();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (countDownDialog != null && countDownDialog.isShowing()) {
                    countDownDialog.dismiss();
                }
            }
        }, 3500);
    }

    /**
     * 选择的模式
     */
    private void initModeOption() {
        switch (getIntent().getIntExtra(IntentFlag.INTENT_FLAG_TYPE,
                SpeechPlayController.LISTENER_MODE_ZHUJU)) {
            // 逐句跟读
            case SpeechPlayController.LISTENER_MODE_ZHUJU:
                speechPlayController = new SpeechPlayController(speechView,
                        SpeechPlayController.LISTENER_MODE_ZHUJU, mUuid, startTime, serviceExpired);
                speechPlayController.setSpeechPlayInterFace(this);
                speechView.setReadMode(SpeechPlayController.LISTENER_MODE_ZHUJU);
                break;
            // 独立通读
            case SpeechPlayController.LISTENER_MODE_DULI:
                speechPlayController = new SpeechIndependentController(
                        speechView, SpeechPlayController.LISTENER_MODE_DULI,
                        mUuid, startTime, serviceExpired);
                speechPlayController.setSpeechPlayInterFace(this);
                speechView.setReadMode(SpeechPlayController.LISTENER_MODE_DULI);
                break;
            // 选段背诵
            case SpeechPlayController.LISTENER_MODE_XUANDUAN:
                speechPlayController = new SpeechIndependentController(
                        speechView, SpeechPlayController.LISTENER_MODE_XUANDUAN,
                        mUuid, startTime, serviceExpired);
                speechPlayController.setSpeechPlayInterFace(this);
                speechView.setReadMode(SpeechPlayController.LISTENER_MODE_XUANDUAN);
                break;
        }
        // 设置是否显示评价
        speechPlayController.setPlayAssess(CWSys.getSharedBoolean(
                EConstants.SHARE_KEY_IS_ASSESS + getUserInfoBase().getUserId(),
                false));
    }

    private boolean isShoudong = false;

    @Override
    protected void loadData() {
        initYzs();
        if (null == mWorkContents || mWorkContents.getExamMode() == 0) {
            //练习模式增加播放全文
            mIsUnAutoMode = true;
            mReadMode = true;
            mIsKaoShiMode = false;
            read_top_play_all.setVisibility(View.GONE);
        } else {
            //考试模式默认自动模式
            mIsUnAutoMode = false;
            mReadMode = false;
            mIsKaoShiMode = true;
            read_top_play_all.setVisibility(View.GONE);
        }
        if (mRlCheckMode.getVisibility() == View.VISIBLE) {
            if (mIsKaoShiMode) {
                //考试模式不显示切换模式按钮
                mIvCheckMode.setVisibility(View.GONE);
            } else {
                boolean isOpenInstentiveReadingMode = CWSys.getSharedBoolean(
                        EConstants.SHARE_KEY_IS_OPEN_SENTENCE_INTENSIVE_READING_MODE,
                        false);
                mIvCheckMode.setSelected(isOpenInstentiveReadingMode);
                //mIsUnAutoMode = isOpenInstentiveReadingMode;
                mIsUnAutoMode = false;
                isShoudong = isOpenInstentiveReadingMode;
                mReadMode = isOpenInstentiveReadingMode;
                //speechView.setmIsReadingMode(mIsUnAutoMode);
            }
        }
        //mIvCheckMode.setVisibility(View.GONE);
        speechView.setmIsReadingMode(mIsUnAutoMode);
        speechView.setisShouDongMode(mIsUnAutoMode);
        speechView.setmIsKaoShiMode(mIsKaoShiMode);
        speechView.setmIsUnAutoMode(mIsUnAutoMode);
        setAutoOrUnautoModle();
        if (EConstants.IS_YOUKE && EConstants.SENTENCE_IS_YOUKE_LOGIN) {
            EConstants.SENTENCE_IS_YOUKE_LOGIN = false;
            loadSentenceDetails(null);
        } else {
            EConstants.SENTENCE_IS_YOUKE_LOGIN = false;
            getSaveSentenceRecord();
        }
    }

    //判断是否有记录 用于设置控件滑动初始位置
    private boolean isHasSentenceRecord = false;

    /**
     * 获取保存的句子记录(用户显示已跟读过的UI)
     */
    protected void getSaveSentenceRecord() {
        SerializableManager.getInstance().deSerialize(
                RepeatKeyUtil.getSaveRepeatAnswerListKey(mDownLoadInfo, mModule,
                        position, intentWorkId, mUuid),

                new BaseCallBack() {
                    @Override
                    public void success(Object data) {
                        ArrayList<SentenceAnswerBean> answerList = (ArrayList<SentenceAnswerBean>) data;
                        if (answerList != null && answerList.size() > 0) {
                            /*
                             * countTime = answerList.get(answerList.size() - 1)
                             * .getCountTime();
                             */
                            isHasSentenceRecord = true;
                            speechPlayController.setSentenceAnswers(answerList);
                            speechPlayController.isContinueFromRecord = true;
                            speechPlayController.showSoundDetectTipsIndex = answerList
                                    .size() + 3;

                        }
                        loadSentenceDetails(null);
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        failed(null);
                    }

                    @Override
                    public void failed(Object data) {
                        loadSentenceDetails(null);
                    }
                });
    }

    /**
     * 播放
     */
    protected void playImg() {
        // 播放状态
        try {
            LinearLayout linearLayout = new LinearLayout(this);
            int lastItemHei = speechView.getContainer().getChildAt(speechView.getContainer().getChildCount() - 1).getHeight();
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, speechView.getHeight() - lastItemHei);
            speechView.getContainer().addView(linearLayout, lp);
            if (!mIsUnAutoMode) {
                int tempIndexx = speechPlayController
                        .getCurrentListenAndRepeatIndex();
                if (speechPlayController.getCurrentListenAndRepeatIndex() == 0) {
                    setNo(0, sentencesDetails.size());
                    if (tempIndexx >= (sentencesDetails.size())) {
                        // 最后一个读完
                        lastSave();
                        return;
                    }
                }
            } else {

                int tempIndex = speechPlayController
                        .getCurrentListenAndRepeatIndex();
                // 这些代码用来解决 暂停之后播放顺序问题 如果已经打完分 暂停之后将直接进入下一个
                if (!currText.getText().toString().equals(++tempIndex + "")) {
                    if (null != sentencesDetails) {
                        setNo(--tempIndex, sentencesDetails.size());
                        if (tempIndex >= (sentencesDetails.size())) {
                            // 最后一个读完
                            lastSave();
                            return;
                        }
                    }
                }
            }
            startPlay();
        } catch (NullPointerException e) {
            e.getStackTrace();
        }

    }

    /**
     * 自动模式开始播放
     */
    protected void startPlay() {
        if (speechPlayController
                .getCurrentListenAndRepeatIndex() < sentencesDetails.size()) {
            speechPlayController.setIsPause(false);
            playOrPause(false);
            startImg.setTag("pa");
            startImg.setImageResource(R.mipmap.type_time_out);
        }
    }

    /**
     * 手动模式开始播放
     */
    protected void startUnAutoPlay() {
        if (speechPlayController
                .getCurrentListenAndRepeatIndex() < sentencesDetails.size()) {
            speechPlayController.setIsPause(false);
            playOrPause(false);
        }
    }

    /**
     * 暂停
     */
    protected void stopImg(boolean isFinish) {
        if (null != speechView.getContainer() && speechView.getContainer().getChildCount() > 0) {
            if (!isFinish) {
                speechView.getContainer().removeViewAt(speechView.getContainer().getChildCount() - 1);
            }
        }
        speechView.stopCount();
        if (!speechPlayController.isPause()) {
            // 暂停状态
            if (speechPlayController != null) {
                speechPlayController.setIsPause(true);
                refreshSpeechView(isFinish);
            }
            if (startImg != null) {
                startImg.setTag("play");
                startImg.setImageResource(R.mipmap.play);
            }
            if (finishRecodeText != null
                    && finishRecodeText.getVisibility() == View.VISIBLE) {
                finishRecodeText.setVisibility(View.GONE);
            }
            if (!mIsUnAutoMode) {
                // 改变计数量 如果已经打完分 则index加1
                speechPlayController.pauseStateChange();
            }
        }
    }

    private void showCheckModeDailog(final boolean isIntensiveReadingModeOpen) {
        CWDialog mDialog = new CWDialog(this);
        String dialogTips;
        if (isIntensiveReadingModeOpen) {
            dialogTips = getString(
                    R.string.instenive_reading_dialog_close_tips);
        } else {
            dialogTips = getString(R.string.instenive_reading_dialog_open_tips);
        }
        // mDialog.setTitle(R.string.lear_title);
        mDialog.setMessage(dialogTips)
                .setPositiveButton(android.R.string.cancel, null)
                .setNegativeButton(R.string.sure,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {

                                mIvCheckMode.setSelected(
                                        !mIvCheckMode.isSelected());
                                mIsUnAutoMode = !isIntensiveReadingModeOpen;
                                speechView.setmIsUnAutoMode(mIsUnAutoMode);
                                mReadMode = !isIntensiveReadingModeOpen;
                                speechView.setmIsReadingMode(mIsUnAutoMode);
                                // refreshSpeechView(true);
                                setAutoOrUnautoModle();
                                CWSys.setSharedBoolean(
                                        EConstants.SHARE_KEY_IS_OPEN_SENTENCE_INTENSIVE_READING_MODE,
                                        mIsUnAutoMode);
                                if (mIsUnAutoMode) {
                                    refreshSpeechView(true);
                                    startUnAutoPlay();

                                } else {
                                    refreshSpeechView(true);
                                    playImg();
                                }
                                setScoreAndNextStatus();
                            }
                        })
                .show();

    }

    /**
     * 设置手动或者自动模式
     */
    protected void setAutoOrUnautoModle() {
        if (mIsUnAutoMode) {
            // 手动模式
            startImg.setVisibility(View.GONE);
            if (readMode == SpeechPlayController.LISTENER_MODE_ZHUJU) {
                play_iocn.setVisibility(View.VISIBLE);
            } else {
                play_iocn.setVisibility(View.GONE);
            }
            img_micro_recording.setVisibility(View.VISIBLE);
            play_dubing_iocn.setVisibility(View.GONE);
            playAllView.setVisibility(View.GONE);
            next_record.setVisibility(View.INVISIBLE);
            back_record.setVisibility(View.VISIBLE);
            stateView.setUnAutoRecordState(true);
        } else {
            // 自动模式
            startImg.setVisibility(View.VISIBLE);
            play_iocn.setVisibility(View.GONE);
            img_micro_recording.setVisibility(View.GONE);
            play_dubing_iocn.setVisibility(View.GONE);
            playAllView.setVisibility(View.VISIBLE);
            next_record.setVisibility(View.GONE);
            back_record.setVisibility(View.GONE);
            stateView.setUnAutoRecordState(false);
        }
        if (speechPlayController != null) {
            speechPlayController.setmIsUnAutoMode(mIsUnAutoMode);
        }
    }

    /**
     * 播放或者暂停界面刷新
     *
     * @param isPlayAll
     */
    public void playOrPause(boolean isPlayAll) {
        boolean start = speechPlayController.start();
        if (start) {
            addSentenceToView(
                    speechPlayController.getCurrentListenAndRepeatIndex(), true,
                    false, isPlayAll, false);
        }
    }

    /**
     * 重新刷新界面
     *
     * @param currIndex
     * @param isPlayState
     * @param isNeedReset
     * @param isFromPlayAll
     * @param isPlayAll
     */
    protected void addSentenceToView(int currIndex, boolean isPlayState,
                                     boolean isNeedReset, boolean isFromPlayAll, boolean isPlayAll) {
        if (mIsUnAutoMode) {
            speechView.addSentenceToView(currIndex, isPlayState, isNeedReset,
                    isFromPlayAll, serviceExpired);
            speechView.toTop();
        } else {
            if (isHasSentenceRecord) {
                for (int i = 0; i < speechPlayController.getSentenceAnswers().size(); i++) {
                    speechView.addSentenceToView(i, true);
                    speechView.nextCount(currIndex, mIsUnAutoMode);
                }
                isHasSentenceRecord = false;
            }
            speechView.addSentenceToView(currIndex, isPlayState);
        }
        if (isShoudong) {
            stopRecord();
            mIvCheckMode.setSelected(
                    mIvCheckMode.isSelected());
            mIsUnAutoMode = isShoudong;
            speechView.setmIsUnAutoMode(mIsUnAutoMode);
            mReadMode = isShoudong;
            isShoudong = false;
            speechView.setmIsReadingMode(mIsUnAutoMode);
            // refreshSpeechView(true);
            setAutoOrUnautoModle();
            CWSys.setSharedBoolean(
                    EConstants.SHARE_KEY_IS_OPEN_SENTENCE_INTENSIVE_READING_MODE,
                    mIsUnAutoMode);
            if (mIsUnAutoMode) {
                refreshSpeechView(true);
                startUnAutoPlay();

            }
            setScoreAndNextStatus();
        }


    }

    /**
     * 初始化库
     */
    protected void initYzs() {
        // showMiddleProgressBar(getTitleText());
        initModeOption();
        sentenceResultScoreController = new SentenceResultScoreController(SentenceRepeatActivity.this, mUuid, startTime, serviceExpired);
        sentenceResultScoreController.setSentenceResultInterFace(this);
    }

    // /**
    // * 获取保存的uuid的key
    // *
    // * @return
    // */
    // protected String getUuidSaveKey() {
    // String key = ESystem.getSaveRecordKey(mDownLoadInfo, mModule, position,
    // intentWorkId,
    // SerializableManager.SerializeKey.SHARE_KEY_UUID_RECORD);
    // return key + "_" + getUserInfoBase().getUserId();
    // }

    /**
     * 获取句子
     */
    public void loadSentenceDetails(final String saveUUid) {

        try {
            EpaperDao.getInstance().getSerializableObjects(resourcePath,
                    new TypeToken<List<SentencesDetail>>() {
                    }.getType(),
                    new BaseExtCallBack(SentenceRepeatActivity.this,
                            EApplication.getInstance().getUserInfoBase()
                                    .getUserId() + "") {

                        @Override
                        public void success(final Object data) {
                            super.success(data);
                            ArrayList<SentencesDetail> tempSentences = (ArrayList<SentencesDetail>) data;
                            // 注释掉的是有选题的部分
                            if (!TextUtils.isEmpty(checkedResource)) {
                                // 有选题
                                String[] checkedSentences = checkedResource
                                        .split(",");
                                sentencesDetails = new ArrayList<SentencesDetail>();
                                for (String checkedVersionId : checkedSentences) {
                                    SentencesDetail sd = new SentencesDetail();
                                    sd.setVersionId(checkedVersionId);
                                    int index = tempSentences.indexOf(sd);
                                    if (index != -1) {
                                        sentencesDetails
                                                .add(tempSentences.get(index));
                                    }
                                }
                            } else {
                                sentencesDetails = tempSentences;
                            }

                            if (sentencesDetails != null
                                    && !sentencesDetails.isEmpty()) {

                                refreshSentencesUi(saveUUid);
                            }
                        }

                        @Override
                        public void failed(int errorCode, Object data) {
                            super.failed(errorCode, data);
                        }

                        @Override
                        public void failed(Object data) {
                            finish();
                            showToastError((int) data);
                        }
                    });

        } catch (NullPointerException e) {
            e.getStackTrace();
        }
    }

    @Override
    public void scoreError() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtil.INSTANCE.toastCenterError(R.string.submit_fail);
            }
        });
    }

    /**
     * 刷新显示句子ui
     */
    protected void refreshSentencesUi(String saveUUid) {
        // 这种情况是之前跟读完成了没有提交就退出界面了
        speechView.setInSentenceAll(isInSentenceAll);
        speechView.setmIsReadingMode(mIsUnAutoMode);
        bindAfData();
        showContent(saveUUid);
        showReLine();

        if (speechPlayController != null
                && speechPlayController.getSentenceAnswers() != null) {
            setNo(speechPlayController.getSentenceAnswers().size(),
                    sentencesDetails.size());
            speechPlayController.setInSentenceAll(isInSentenceAll);
            if (mIsUnAutoMode) {
                refreshSpeechView(true);
                startUnAutoPlay();
            }
        } else {
            setNo(0, sentencesDetails.size());
        }

    }

    /**
     * 设置跟读结果页面item之间的横线
     */
    private void showReLine() {
        if (speechPlayController.getSentenceAnswers() != null
                && sentencesDetails.size() == speechPlayController
                .getSentenceAnswers().size()) {
            if (speechView != null) {
                speechView.showLine();
            }
        }
    }

    /**
     * 绑定之前的数据
     */
    protected void bindAfData() {
        if (speechPlayController.getSentenceAnswers() != null
                && sentencesDetails.size() == speechPlayController
                .getSentenceAnswers().size()) {
            // 说明之前已经跟读完成了
            mIsUnAutoMode = false;
            speechView.setmIsReadingMode(false);
            speechView.setAllComplete(true);

            if (speechPlayController != null) {
                speechPlayController.setIsPause(true);
            }
            stopImg(false);
            showUpView();

            isBackSave = false;
        }
        if (!(speechPlayController.getSentenceAnswers() != null
                && sentencesDetails.size() == speechPlayController
                .getSentenceAnswers().size())) {
            showHelp();
            sumView.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 点击提交按钮后重新评分
     */
    public void scoreReTryCommit() {
        Sentence sentence = new Sentence();
        boolean isLastOne = false;
        for (int i = 0; i < mScoreSentence.size(); i++) {
            if (mScoreSentence.size() == 1) {
                sentence = mScoreSentence.get(i);
                isLastOne = true;
                //scoreReTry(true, sentences.get(i));
                mScoreSentence.remove(i);
            } else {
                sentence = mScoreSentence.get(i);
                isLastOne = false;
                //scoreReTry(false, sentences.get(i));
                mScoreSentence.remove(i);
                break;
            }
        }

        SentenceAnswerBean sentenceAnswerBean = new SentenceAnswerBean();
        ArrayList<SentenceAnswerBean> sentenceAnswers = speechPlayController.getSentenceAnswers();
        for (int i = 0; i < sentenceAnswers.size(); i++) {
            if (sentenceAnswers.get(i).getSentence().getTextId().equals(sentence.getTextId())) {
                sentenceAnswerBean = sentenceAnswers.get(i);
                break;
            }
        }
        sentenceResultScoreController.scoreReTry(sentenceAnswerBean, sentence, isLastOne, true);

    }

    /**
     * 重新评分
     *
     * @param
     * @param isLastOne
     */
    public void scoreReTry(boolean isLastOne, Sentence sentence) {
        showCricleProgress("正在打分。。。");
        SentenceAnswerBean sentenceAnswerBean = new SentenceAnswerBean();
        ArrayList<SentenceAnswerBean> sentenceAnswers = speechPlayController.getSentenceAnswers();
        for (int i = 0; i < sentenceAnswers.size(); i++) {
            if (sentenceAnswers.get(i).getSentence().getTextId().equals(sentence.getTextId())) {
                sentenceAnswerBean = sentenceAnswers.get(i);
                break;
            }
        }
        sentenceResultScoreController.scoreReTry(sentenceAnswerBean, sentence, isLastOne, false);

    }

    public void addScoreCount() {
        hideCricleProgress();
        countIsScoreAll++;
    }

    /**
     * 重新评分后设置分数
     *
     * @param sentenceAnswerBean
     * @param isLastOne
     */
    @Override
    public void setScoreResultReTry(SentenceAnswerBean sentenceAnswerBean, boolean isLastOne, boolean isubmitAll) {
        if (allScoreCount != 0) {
            hasScoreCount++;
            if (countIsScoreAll == allScoreCount) {
                if (null != scoreTipsDialog) {
                    scoreTipsDialog.dismiss();
                }
            } else {
                showTips();
            }
        }
        for (int i = 0; i < speechPlayController.getSentenceAnswers().size(); i++) {
            if (speechPlayController.getSentenceAnswers().get(i).getSentence().getTextId().equals(sentenceAnswerBean.getSentence().getTextId())) {
                speechPlayController.getSentenceAnswers().set(i, sentenceAnswerBean);
                break;
            }
        }
        for (int i = 0; i < speechPlayController.getSentences().size(); i++) {
            if (speechPlayController.getSentences().get(i).getTextId().equals(sentenceAnswerBean.getSentence().getTextId())) {
                speechPlayController.getSentences().get(i).setScore(sentenceAnswerBean.getSentence().getScore());
                speechPlayController.getSentences().get(i).setHasGrade(true);
                break;
            }
        }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showContent(null);
                speechPlayController.refreshAllSpeechView(true);
            }
        });

        if (countIsScoreAll == allScoreCount || allScoreCount == 0) {
            hasScoreCount = 0;
            countIsScoreAll = 0;
            allScoreCount = 0;
                    /*showContent(null);
                    speechPlayController.refreshAllSpeechView(true);*/

        }
        if (hasScoreCount == allScoreCount && isubmitAll) {
            submitWork();
            hasScoreCount = 0;
            countIsScoreAll = 0;
            allScoreCount = 0;
        }

    }

    @Override
    public void reFresh() {
        hasScoreCount = 0;
        countIsScoreAll = 0;
        allScoreCount = 0;
        if (null != mScoreSentence) {
            mScoreSentence.clear();
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (null != scoreTipsDialog && scoreTipsDialog.isShowing()) {
                    scoreTipsDialog.dismiss();
                }
                showContent(null);
                speechPlayController.refreshAllSpeechView(true);
                ToastUtil.INSTANCE.toastCenterError("提交失败，请重新提交");
            }
        });


    }

    private void showTopTip() {
        if (speechPlayController.getSentenceAnswers().size() != sentencesDetails
                .size() && speechPlayController.getSentenceAnswers().size() > 0) {
            studentRel.setVisibility(View.VISIBLE);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    studentRel.setVisibility(View.GONE);
                }
            }, 2000);
        }
    }

    /**
     * 显示句子的序号
     *
     * @param currIndex
     * @param count
     */
    protected void setNo(int currIndex, int count) {
        setengLishChina(currIndex);
        currIndex = currIndex + 1;
        if (currIndex > count) {
            currIndex = count;
        }
        currText.setText(currIndex + "");
        countText.setText("/" + count);
        double mid = (double) currIndex / (double) count;
        int progressCount = (int) (mid * 100);
        progressBar.setProgress(progressCount);
    }

    /**
     * 显示句子的中文翻译图标
     *
     * @param currIndex
     */
    protected void setengLishChina(int currIndex) {
        if (currIndex >= sentencesDetails.size()) {
            return;
        }
        SentencesDetail item = sentencesDetails.get(currIndex);
        if (item.getTranslate() != null && item.getTranslate() != "") {
            iv_english_china.setVisibility(View.VISIBLE);
        } else {
            iv_english_china.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化视图将句子一个一个添加的Lin控件上
     *
     * @param saveUUid
     */
    protected void showContent(String saveUUid) {
        try {
            boolean success = speechPlayController.setParagraphText(
                    sentencesDetails, mVerisonId, saveUUid, stateView,
                    play_iocn, getUserInfoBase().getUserId(),
                    speechPlayController.sentences.isEmpty());
            if (!success) {
                showToastError(R.string.speek_error);
                return;
            }

        } catch (NullPointerException e) {
            e.getStackTrace();
        }

    }

    // 播放流程接口

    /**
     * 播放下一个的回调
     *
     * @param currentIndex
     * @param isPrevious   是否是上一步
     */
    @Override
    public void nextPlay(int currentIndex, int count, boolean isPrevious) {
        if (currentIndex < count) {
            /*if (mIsUnAutoMode) {
                speechView.nextCount();
            }*/
            if (isPrevious) {
                //speechView.previousCount();
            } else {
                speechView.nextCount(currentIndex, mIsUnAutoMode);
            }
            setNo(currentIndex, count);
            addSentenceToView(currentIndex, true, false, false, false);
            setScoreAndNextStatus();
        }
    }

    /**
     * 设置按钮状态
     */
    private void setScoreAndNextStatus() {
        if (mIsUnAutoMode) {
            int curr = speechPlayController.getCurrentListenAndRepeatIndex();
            ArrayList<SentenceAnswerBean> sentenceAnswers = speechPlayController
                    .getSentenceAnswers();
            try {
                if (curr < sentenceAnswers.size()) {
                    // 有录音，显示结果，可以点击下一个
                    SentenceAnswerBean mcurr = speechPlayController
                            .getSentenceAnswers().get(curr);
                    scoreResult(mcurr.getSentence().getScore(), mcurr.getSentence().getIntegrity(), mcurr.getSentence().getFluency(), mcurr.getSentence().getPronunciation(), mcurr);
                    EvaluateResult evaluateResult = JsonParserUtil
                            .fromJson(mcurr.getLines(), EvaluateResult.class);
                    speechView.showResult(evaluateResult,
                            speechPlayController.getSentences()
                                    .get(speechPlayController
                                            .getCurrentListenAndRepeatIndex()),
                            false, serviceExpired);
                    setResultScoreStatus(mcurr);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            scoreRel.setVisibility(View.GONE);
            accuracy_text.setVisibility(View.GONE);
            smooth_text.setVisibility(View.GONE);
            completion_text.setVisibility(View.GONE);
            see_work_score_text.setVisibility(View.GONE);
        }
    }

    /**
     * 显示提交界面
     */
    private void showUpView() {
        isFinish = true;
        upWorkText.setVisibility(View.VISIBLE);
        playRel.setVisibility(View.GONE);
        speechView.showOrCloseStress(0);
        if (playAllView != null) {
            // 读完之后播放全文按钮是没有的
            playAllView.setVisibility(View.INVISIBLE);
        }
        if (sumView != null) {
            sumView.setVisibility(View.GONE);
        }
        if (!serviceExpired && "setBuyServiceDialog" != "setBuyServiceDialog") {
            String text = "查看分数";
            SpannableString spannableString = new SpannableString(text);
            // 定义颜色（例如红色）
            int color = getResources().getColor(R.color.color_light_green);
            // 创建 ForegroundColorSpan 对象
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(color);
            spannableString.setSpan(colorSpan, 0, text.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(new UnderlineSpan(), 0, text.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
            setRightSpannaText(spannableString);
            setRightBtnEnable(true);
            setRightBtnListener(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    setBuyServiceDialog();
                }
            });
        }
    }

    @Override
    public void scoreResult(int score, float integrity, float fluency, float pronunciation, SentenceAnswerBean mSentenceAnswerBean) {
        if (serviceExpired) {
            int color;
            int image;
            if (score < SpeechUtils.TOTAL_SCORE_1) {
                color = R.color.score_red;
                image = R.mipmap.score_red_rep;
            } else if (score < SpeechUtils.TOTAL_SCORE_3) {
                color = R.color.score_yellow;
                image = R.mipmap.score_orange_rep;
            } else {
                color = R.color.score_green_word;
                image = R.mipmap.score_green_rep;
            }
            if (score == -1) {
                scoreText.setVisibility(View.GONE);
            } else {
                scoreText.setVisibility(View.VISIBLE);
                scoreText.setText(score + "");
            }
            int changeIntegrity = (int) integrity;
            int changeFluency = (int) fluency;
            int changePronunciation = (int) pronunciation;
            int integrityColor;
            int fluencyColor;
            int pronunciationColor;
            if (changeIntegrity < SpeechUtils.TOTAL_SCORE_1) {
                integrityColor = R.color.score_red;
            } else if (changeIntegrity < SpeechUtils.TOTAL_SCORE_3) {
                integrityColor = R.color.score_yellow;
            } else {
                integrityColor = R.color.score_green_word;
            }

            if (changeFluency < SpeechUtils.TOTAL_SCORE_1) {
                fluencyColor = R.color.score_red;
            } else if (changeFluency < SpeechUtils.TOTAL_SCORE_3) {
                fluencyColor = R.color.score_yellow;
            } else {
                fluencyColor = R.color.score_green_word;
            }

            if (changePronunciation < SpeechUtils.TOTAL_SCORE_1) {
                pronunciationColor = R.color.score_red;
            } else if (changePronunciation < SpeechUtils.TOTAL_SCORE_3) {
                pronunciationColor = R.color.score_yellow;
            } else {
                pronunciationColor = R.color.score_green_word;
            }
            SpannableString completionText = new SpannableString(getString(R.string.completionText, changeIntegrity + ""));
            SpannableString smoothText = new SpannableString(getString(R.string.smoothText, changeFluency + ""));
            SpannableString accuracyText = new SpannableString(getString(R.string.accuracyText, changePronunciation + ""));
            ForegroundColorSpan colorintegrity = new ForegroundColorSpan(getResources().getColor(integrityColor));
            ForegroundColorSpan colorfluency = new ForegroundColorSpan(getResources().getColor(fluencyColor));
            ForegroundColorSpan colorpronunciation = new ForegroundColorSpan(getResources().getColor(pronunciationColor));
            completionText.setSpan(colorintegrity, 4, getString(R.string.completionText, changeIntegrity + "").length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            smoothText.setSpan(colorfluency, 4, getString(R.string.smoothText, changeFluency + "").length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            accuracyText.setSpan(colorpronunciation, 4, getString(R.string.accuracyText, changePronunciation + "").length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            completion_text.setText(completionText);
            smooth_text.setText(smoothText);
            accuracy_text.setText(accuracyText);
            scoreText.setTextColor(getResources().getColor(color));
            scoreTextView.setTextColor(getResources().getColor(color));
            scoreIma.setImageResource(image);
            see_work_score_text.setVisibility(View.GONE);
            scoreRel.setVisibility(View.VISIBLE);
            accuracy_text.setVisibility(View.VISIBLE);
            smooth_text.setVisibility(View.VISIBLE);
            completion_text.setVisibility(View.VISIBLE);
            if (!mIsUnAutoMode) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        scoreRel.setVisibility(View.GONE);
                        accuracy_text.setVisibility(View.GONE);
                        smooth_text.setVisibility(View.GONE);
                        completion_text.setVisibility(View.GONE);
                    }
                }, 2000);
            }
        } else {
            scoreText.setVisibility(View.VISIBLE);
            scoreText.setText("已提交");
            scoreText.setTextColor(getResources().getColor(R.color.color_light_green));
            scoreText.setTextSize(18);
            scoreIma.setVisibility(View.GONE);
            see_work_score_text.setVisibility(View.VISIBLE);
            scoreRel.setVisibility(View.VISIBLE);
            scoreTextView.setVisibility(View.GONE);
            accuracy_text.setVisibility(View.GONE);
            smooth_text.setVisibility(View.GONE);
            completion_text.setVisibility(View.GONE);
            if (!mIsUnAutoMode) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        scoreRel.setVisibility(View.GONE);
                        accuracy_text.setVisibility(View.GONE);
                        smooth_text.setVisibility(View.GONE);
                        completion_text.setVisibility(View.GONE);
                        see_work_score_text.setVisibility(View.GONE);
                    }
                }, 2000);
            }
        }
        isRecording = false;
    }


    @Override
    protected void onPause() {
        // 暂停
        isCanPlay = false;
        stopImg(true);
        cancelRecord();
        speechView.playUnAto(false);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        try {

            if (speechPlayController != null) {
                speechPlayController.setIsPause(true);
                if (isNeedSaveAn()) {
                    if (speechPlayController.getSentenceAnswers() != null
                            && speechPlayController.getSentenceAnswers()
                            .size() > 0
                            && sentencesDetails != null
                            && speechPlayController.getSentenceAnswers()
                            .size() != sentencesDetails.size()) {
                        speechPlayController
                                .getSentenceAnswers().get(speechPlayController
                                .getSentenceAnswers().size() - 1)
                                .setCountTime(countTime);
                    }
                    onSaveSentenceRecord(
                            speechPlayController.getSentenceAnswers());

                    SpeechPlayController.readCount = 0;
                }
            }

        } catch (NullPointerException e) {
            e.getStackTrace();
        }

        super.onDestroy();
    }

    /**
     * 退出时是否需要保存答案 默认不保存
     *
     * @return
     */
    protected boolean isNeedSaveAn() {
        return true;
    }

    @Override
    public void close() {
        if (isCanPlay) {
            showTopTip();
            playImg();
        }
    }

    @Override
    protected void onResume() {
        isCanPlay = true;
        super.onResume();
    }

    protected void showDialog() {
        stopImg(true);
        if (isBackSave) {
            SpeechPlayController.readCount--;
            CWDialog mDialog = new CWDialog(this);
            // mDialog.setTitle(R.string.lear_title);
            mDialog.setMessage(R.string.confirm_back_work);
            mDialog.setPositiveButton(android.R.string.cancel, null);
            mDialog.setNegativeButton(R.string.ok,
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            finish();
                        }
                    });
            // }
            mDialog.show();
        } else {
            finish();
        }
    }

    public void onSaveSentenceRecord(ArrayList<SentenceAnswerBean> answerList) {
        if (answerList != null && answerList.size() > 0) {
            if (answerList.size() > sentencesDetails.size()) {
                answerList = null;
            }

            // String key = ESystem.getSaveRecordKey(mDownLoadInfo, mModule,
            // position, intentWorkId,
            // SerializableManager.SerializeKey.SHARE_KEY_SENTENCE_RECORD +
            // typeMode);

            String key = RepeatKeyUtil.getSaveRepeatAnswerListKey(mDownLoadInfo,
                    mModule, position, intentWorkId, mUuid);
            SerializableManager.getInstance().serialize(key, answerList);

        }
    }

    /**
     * 每次读完一次就把录音信息添加到阿里云
     *
     * @param sentenceAnswerBean
     * @param index
     */
    @Override
    public void addResult(SentenceAnswerBean sentenceAnswerBean, int index) {
        if (EConstants.IS_YOUKE) {
            // do nothing
        } else {
            ALiYunManager.getInstance().addMP3(sentenceAnswerBean.getSoundUrl(),
                    sentenceAnswerBean.getSoundUrl(), startTime);
        }

        CWLog.d("aliyun", "提交" + System.currentTimeMillis() + "tag="
                + sentenceAnswerBean.getSoundUrl() + index);
    }

    /**
     * 打分完之后的回调
     *
     * @param currentIndex
     * @param count
     */
    @Override
    public void lastRecord(int currentIndex, int count) {
        setNo(currentIndex, count);
        if (currentIndex >= (count - 1)) {
            // 代表已经读完了
            lastSave();
        }
    }

    /**
     * 获取作业用时key
     *
     * @return
     */
    protected String getSaveTime() {
        String key = ESystem.getSaveRecordKeywithMode(mDownLoadInfo, mModule,
                position, intentWorkId,
                SerializableManager.SerializeKey.SHARE_KEY_DO_WORK_TIME,
                readMode);
        return key + "_" + getUserInfoBase().getUserId();
    }

    /**
     * 读完，保存作业
     */
    private void lastSave() {
        mIsUnAutoMode = false;
        speechView.setmIsReadingMode(false);
        speechView.setAllComplete(true);
        countTime = System.currentTimeMillis() - startDate;
        CWSys.setSharedLong(getSaveTime(), countTime);
        if (speechPlayController.isPause()) {
            refreshSpeechView(false);
        }
        stopImg(false);
        showUpView();
        showReLine();
        if (speechPlayController.getSentenceAnswers() != null
                && speechPlayController.getSentenceAnswers().size() > 0) {
            speechPlayController.getSentenceAnswers()
                    .get(speechPlayController.getSentenceAnswers().size() - 1)
                    .setCountTime(countTime);
        }
        onSaveSentenceRecord(speechPlayController.getSentenceAnswers());
    }


    /**
     * 重读事件的回调
     *
     * @param v
     * @param relativeLayout
     */
    @Override
    public void stress(View v, RelativeLayout relativeLayout) {
        try {
            AudioPlayer.getInstance().stop();
            int index = speechView.getIndexByView(relativeLayout);
            ArrayList<SentencesDetail> temp = new ArrayList<>();
            if (null != sentencesDetails && sentencesDetails.size() > index) {
                temp.add(sentencesDetails.get(index));
            }
            ArrayList<SentenceAnswerBean> anList = new ArrayList<>();
            if (null != speechPlayController.getSentenceAnswers() && speechPlayController.getSentenceAnswers().size() > index) {
                anList.add(speechPlayController.getSentenceAnswers().get(index));
            }
            /*EpaperJumpManager.jumpToSentenceStress(R.string.go_back, this, temp,
                    anList, index, REQUEST_CODE_AN, mModule, position, readMode,
                    mDownLoadInfo, mIsUnAutoMode);*/
            EpaperJumpManager.jumpToSentenceStress(R.string.go_back, this, temp,
                    anList, index, REQUEST_CODE_AN, mModule, position, readMode,
                    mDownLoadInfo, mReadMode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void stressItemClick(View v, RelativeLayout relativeLayout) {

        // if (speechPlayController.getSentenceAnswers().size() >=
        // sentencesDetails.size()) {
        speechView.showOrCloseStress(speechView.getIndexByView(relativeLayout));
        // }

    }

    private ImageView mLastPlayIcon;

    @Override
    public void stressIconRec(View v, RelativeLayout relativeLayout) {
        int index = speechView.getIndexByView(relativeLayout);

        if (null != mLastPlayIcon) {
            AudioPlayer.getInstance().stop();
            ((AnimationDrawable) mLastPlayIcon.getDrawable()).stop();
            mLastPlayIcon.setImageResource(R.mipmap.icon_sound_gray);
        }

        ImageView imageView = (ImageView) v;
        mLastPlayIcon = imageView;

        imageView.setImageResource(R.drawable.reread_bg_annimation);
        final AnimationDrawable animationDrawable = (AnimationDrawable) imageView
                .getDrawable();
        animationDrawable.start();

        String soundUrl = speechPlayController.getSentenceAnswers().get(index)
                .getSoundUrl();
        File file = new File(soundUrl);
        if (file == null || !file.exists()) {
            soundUrl = FileUtil.getReNameFilePath(soundUrl);
        }
        AudioPlayer.getInstance().setOnPlayListener(new OnPlayListener() {
            @Override
            public void onReadPlayer(long l, Object o) {

            }

            @Override
            public void onPlayStart(Object o) {

            }

            @Override
            public void stop(Object o) {
                animationDrawable.stop();
            }

            @Override
            public void onError(int i, Object o) {
                animationDrawable.stop();
            }

            @Override
            public void onBuffer(Object o, long l, long l1) {

            }

            @Override
            public void onPlaying(long l, long l1) {

            }
        }).play(BaseConstants.FILE_PREFIX + soundUrl, null);
        try {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M
                    && EApplication.getInstance().mPlayerspeed != 1.0f) {
                MediaPlayer mMediaPlayer = AudioPlayer.getInstance()
                        .getMediaPlayer();
                if (mMediaPlayer != null) {
                    try {
                        PlaybackParams params = mMediaPlayer.getPlaybackParams()
                                .setSpeed(EApplication
                                        .getInstance().mPlayerspeed);
                        if (params != null) {
                            mMediaPlayer.setPlaybackParams(params);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void startRecord() {
        isRecording = true;
        if (!mIsUnAutoMode) {
            // 开始录音
            if (finishRecodeText != null) {
                showFirstRec();
                finishRecodeText.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 取消测评
     */
    public void cancelRecord() {
        if (!isRecording) {
            return;
        }
        speechPlayController.cancelRecord();
        // 停止录音
        handler.post(new Runnable() {
            @Override
            public void run() {
                finishRecodeText.setVisibility(View.GONE);
                stateView.closeView(mIsUnAutoMode);
                // stateView. complateRecorde();
            }
        });
        isRecording = false;
    }

    @Override
    public void stopRecord() {
        // 停止录音
        handler.post(new Runnable() {
            @Override
            public void run() {
                finishRecodeText.setVisibility(View.GONE);
                stateView.closeView(mIsUnAutoMode);
                // stateView. complateRecorde();
            }
        });
    }


    @Override
    public void recError(IOralEvalSDK evalSDK, final SDKError sdkError,
                         IOralEvalSDK.OfflineSDKError offlineSDKError) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                SDKError.Category category = sdkError.category;
                if (mIsUnAutoMode && SDKError.Category.Device != category) {
                    next_record.setVisibility(View.VISIBLE);
                }
                if (SDKError.Category.Network == category) {
                    if (!NetworkUtils.isOnline()) {
                        //ToastUtil.INSTANCE.toastCenterNoNetError();
                        ToastUtil.INSTANCE.toastTopError(R.string.connect_disable5);
                    } else {
                        /*ToastUtil.INSTANCE.toastCenterError(
                                "评分过程遇到错误，错误信息：" + sdkError.errno);*/
                        //ToastUtil.INSTANCE.toastTopError(R.string.connect_disable5);
                        ToastUtil.INSTANCE.toastTopError(getString(R.string.connect_disable7) + "(" + sdkError.errno + ")", Toast.LENGTH_SHORT);
                    }
                } else if (SDKError.Category.Device == category) {
                    DialogUtil.showSettingPermissions(
                            SentenceRepeatActivity.this);
                } else {
                    /*ToastUtil.INSTANCE.toastCenterError(
                            "评分过程遇到错误，错误信息：" + sdkError.errno);*/
                    ToastUtil.INSTANCE.toastTopError(getString(R.string.connect_disable7) + "(" + sdkError.errno + ")", Toast.LENGTH_SHORT);
                }
                //stopImg(true);
            }
        });
        String logDesc = "云之声评分失败###errorCode####" + sdkError.toString();
        FeedbackUtil.getInstance().addFeedbackLog(
                FeedbackUtil.FEEDBACK_TYPE_EVALUATE, logDesc, "评分失败");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && isBack()) {
            // 返回键监听
            showDialog();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 是否返回拦截
     *
     * @return
     */
    protected boolean isBack() {
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {

        try {

            switch (requestCode) {
                case REQUEST_CODE_AN:
                    if (resultCode == REQUEST_CODE_AN) {
                        ArrayList<SentenceAnswerBean> temp = (ArrayList<SentenceAnswerBean>) data
                                .getSerializableExtra(
                                        IntentFlag.INTENT_FLAG_SENT_AN);
                        List<WordDetail> words = temp.get(0).getSentence()
                                .getWordDetails();

                        int index = data.getIntExtra(
                                IntentFlag.INTENT_FLAG_SENT_INDEX, 0);
                        if (temp.size() > 0) {
                            speechPlayController.getSentenceAnswers().set(index,
                                    temp.get(0));
                        }
                        showContent(null);
                        showReLine();
                    }
                    break;
            }

        } catch (RuntimeException e) {
            e.getStackTrace();
        }

    }

    private void onSaveState(int state) {
        String userId = SerializableManager.getInstance().getUserId(true);
        if (userId != null && !userId.equals("") && !userId.equals(",0")) {
            // String keyTemp = ESystem.getSaveRecordKey(mDownLoadInfo, mModule,
            // position, intentWorkId,
            // SerializableManager.SerializeKey.SHARE_KEY_SENTENCE_STATE +
            // typeMode);
            String keyTemp = RepeatKeyUtil.getSaveSentenceRepeatStatueKey(
                    mDownLoadInfo, mModule, position, intentWorkId, mUuid);
            SerializableManager.getInstance().serialize(keyTemp, state);
        }

    }

    protected void refreshSpeechView(boolean isState) {
        /*if (mIsUnAutoMode) {
            speechPlayController.refreshSpeechView(isState);
        }else {
            speechPlayController.refreshAllSpeechView(isState);
        }*/
        speechPlayController.refreshSpeechView(isState);

    }

    /**
     * 设置分数
     *
     * @param mAnswerRecorder
     */
    @Override
    public void setResultScoreStatus(SentenceAnswerBean mAnswerRecorder) {
        if (!mIsUnAutoMode) {
            return;
        }
        if (mAnswerRecorder != null && mAnswerRecorder.getSoundUrl() != null
                && !mAnswerRecorder.getSoundUrl().equals("")) {
            play_dubing_iocn.setTimeAndPlayBtnState(
                    (long) mAnswerRecorder.getAudioDuration(),
                    PlayStateView.PLAY_STATUE);
            play_dubing_iocn.setVisibility(View.VISIBLE);
            play_dubing_iocn.setTag(mAnswerRecorder.getSoundUrl());
            next_record.setVisibility(View.VISIBLE);
        } else {
            play_dubing_iocn.setTimeAndPlayBtnState(
                    (long) mAnswerRecorder.getAudioDuration(),
                    PlayStateView.PLAY_STATUE);
            play_dubing_iocn.setVisibility(View.GONE);
            next_record.setVisibility(View.GONE);
        }
    }

    @Override
    public void setRecordStatus(Boolean isRecord) {
        isRecording = isRecord;
    }

    /**
     * 设置手动录音是按钮状态
     */
    public void setRecordStatus() {
        if (play_dubing_iocn != null && play_dubing_iocn.isPlay()) {
            play_dubing_iocn.stopOnlyPlay();
        }
        if (mIsUnAutoMode) {
            scoreRel.setVisibility(View.GONE);
            accuracy_text.setVisibility(View.GONE);
            smooth_text.setVisibility(View.GONE);
            completion_text.setVisibility(View.GONE);
            see_work_score_text.setVisibility(View.GONE);
            play_dubing_iocn.setVisibility(View.GONE);
            next_record.setVisibility(View.GONE);
        }
    }

    /**
     * 播放录音
     */
    public void playRecordWord() {
        if (isRecording) {
            return;
        }
        if (AudioPlayer.getInstance().isPlaying()) {
            AudioPlayer.getInstance().stop();
        }
        if (play_dubing_iocn != null) {
            String soundUrl = (String) play_dubing_iocn.getTag();
            File file = new File(soundUrl);
            if (file == null || !file.exists()) {
                soundUrl = FileUtil.getReNameFilePath(soundUrl);
            }
            AudioPlayer.getInstance().setOnPlayListener(mOnPlayListener)
                    .play(BaseConstants.FILE_PREFIX + soundUrl, true);
        }
    }

    /**
     * 播放录音
     */
    private OnPlayListener mOnPlayListener = new OnPlayListener() {
        @Override
        public void onReadPlayer(long duration, Object mp3) {
            play_dubing_iocn.setTimeAndPlayBtnState(duration,
                    PlayStateView.PLAY_STATUE);
        }

        @Override
        public void onPlayStart(Object o) {
            play_dubing_iocn.startPlay();
        }

        @Override
        public void stop(Object o) {
            play_dubing_iocn.stopOnlyPlay();
        }

        @Override
        public void onError(int i, Object o) {
            play_dubing_iocn.stopOnlyPlay();
        }

        @Override
        public void onBuffer(Object o, long l, long l1) {

        }

        @Override
        public void onPlaying(long progress, long max) {

        }
    };
}
